package com.itcast.hadoop.ii;/**
 * Created by Administrator on 2019/4/8 0008.
 */

import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

/**
 * @author ydf
 * @com kt
 * @create 2019-04-08 下午 12:18
 **/
public class InverseIndexStepTwo {

    public static class StepTwoMapper extends Mapper<LongWritable,Text,Text,Text>{
        //K：行起始偏移量 value ：{hello --> a.txt 3}

        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {

            String line=value.toString();
            String[] fileds= StringUtils.split(line,"\t");
            String[] worldAndFileName=StringUtils.split(fileds[0],"-->");
            String word=worldAndFileName[0];
            String fileName=worldAndFileName[1];
            long count=Long.parseLong(fileds[1]);

            //map输出结果是这个形式：<hello,a.txt-->3>
            context.write(new Text(word),new Text(fileName+"-->"+count));
        }
    }

    public static class StepTwoReducer extends Reducer<Text,Text,Text,Text>{
        @Override
        protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
            //拿到数据<hello,{a.txt-->3,b.txt-->2,c.txt-->1}>
            String result ="";
            for(Text value:values){
                result +=value+" ";
            }
            //输出结果就是K: hell0 V: a.txt-->3 b.txt-->2 c.txt-->1
            context.write(key,new Text(result));
        }
    }

    public static void main(String[] args) throws InterruptedException, IOException, ClassNotFoundException {
        Configuration configuration = new Configuration();
        Job job = Job.getInstance(configuration);

        job.setJarByClass(InverseIndexStepTwo.class);

        job.setMapperClass(StepTwoMapper.class);
        job.setReducerClass(StepTwoReducer.class);

        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(Text.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);

        FileInputFormat.setInputPaths(job, new Path(args[0]));

        Path output=new Path(args[1]);
        FileSystem fs =FileSystem.get(configuration);
        if(fs.exists(output)){
            fs.delete(output,true);
        }
        FileOutputFormat.setOutputPath(job, output);

        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }
}
